package pl.kosmowska.ewelina.server.dao;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;

import pl.kosmowska.ewelina.server.jdo.CategoryData;
import pl.kosmowska.ewelina.server.jdo.CategoryItemData;
import pl.kosmowska.ewelina.server.jdo.DatabaseEntity;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;



public class CategoryDataDAO extends JdoDAOImpl<CategoryData> {


	private static final Logger log = Logger.getLogger(CategoryDataDAO.class
			.getName());


	public CategoryData findCategoryData(String id) {
		return (CategoryData) findById(id);

	}

	public  List<CategoryData> findCategoryDataByUser() {
		Long uid = UserDataDAO.getLoggedInUserId();

		String qfilter = "userId==" + uid + "";

		PersistenceManager pm = getPersistenceManager();
		try {
			javax.jdo.Query query = pm.newQuery("select from " + CategoryData.class.getName());
			query.setFilter(qfilter);
			List<CategoryData> list = (List<CategoryData>) query.execute();

			List<CategoryData> r = (List<CategoryData>) pm.detachCopyAll(list);

			return r;
		} catch (Exception e) {
			log.log(Level.SEVERE, "Error: Category.findCategory(): qfilter=" + qfilter, e);
			e.printStackTrace();
		} finally {
			pm.close();
		}
		return null;
	}

	public CategoryData persist(CategoryData categoryData) {
		return (CategoryData) persistEntity(categoryData);

	}

	public Boolean deleteCategoryItemData(String id) {

		if (id == null) {
			return false;
		}
		Long uid = UserDataDAO.getLoggedInUserId();

		Key key = KeyFactory.stringToKey(id);

		Boolean success = false;
		PersistenceManager pm = getPersistenceManager();
		Transaction tx = pm.currentTransaction();
		try {

			CategoryItemData e = pm.getObjectById(CategoryItemData.class, key);
			if (e.getUserId() != uid) { // check owner
				log.severe("CategoryItemData.remove() Error: Something weird going on in setting UID. e.getUserId()=" + e.getUserId() + " uid=" + uid);
				success = false;

			} else {
				tx.begin();
				pm.deletePersistent(e);
				tx.commit();
				success = true;
			}

		} catch (Exception e) {
			log.log(Level.SEVERE, "Error:", e);
			e.printStackTrace();
		} finally {
			if (tx.isActive()) {
				tx.rollback();
				success = false;
			}
			pm.close();
		}

		return success;
	}

	public static void persistDefaultCategoryList(List<CategoryData> categoryDataList) {
		for(CategoryData categoryData: categoryDataList){
			categoryData.setUserId(UserDataDAO.getLoggedInUserId());
		}
		PersistenceManager pm = getPersistenceManager();
		try {
			pm.makePersistentAll(categoryDataList);
		} catch (Exception e) {
			log.log(Level.SEVERE, "Error: CategoryDataDAO.persistDefaultCategoryList()", e);
			e.printStackTrace();
		} finally {
			pm.close();
		}

	}
}